<template>
  <div class="sample-list-bg">
    <div class="sample-list-header">
      <div class="header-top">
        <h2>样品含量查询</h2>
        <div class="user-info" @click="goToProfile">
          <span class="user-name">{{ currentUser.name }}</span>
          <span class="icon">👤</span>
        </div>
      </div>
      <div class="search-bar">
        <div class="search-input-group">
          <input v-model="keyword" @keyup.enter="fetchSamples" placeholder="输入样品名称/编号/年份搜索" />
          <button @click="fetchSamples" class="search-btn">搜索</button>
        </div>
        <button v-if="isLoggedIn && isAdmin" class="add-btn" @click="showAddModal = true">
          <span class="icon">+</span>
          新增样品
        </button>
      </div>
    </div>
    
    <div class="sample-cards">
      <div v-for="item in samples" :key="item.id" class="sample-card">
        <div class="card-header">
          <div class="sample-title">
            <h3>{{ item.sample_name }}</h3>
            <span class="sample-code">{{ item.sample_code }}</span>
          </div>
          <div class="card-actions" v-if="isLoggedIn && isAdmin">
            <button @click="editSample(item)" class="action-btn edit-btn" title="编辑">
              <span class="icon">✏️</span>
            </button>
            <button @click="deleteSample(item.id)" class="action-btn delete-btn" title="删除">
              <span class="icon">🗑️</span>
            </button>
          </div>
        </div>
        
        <div class="card-content">
          <div class="info-row">
            <span class="label">年份:</span>
            <span class="value">{{ item.year }}</span>
          </div>
          <div class="info-row">
            <span class="label">日期:</span>
            <span class="value">{{ formatDate(item.date) }}</span>
          </div>
          <div class="content-details">
            <span class="label">含量信息:</span>
            <div class="content-items">
              <div v-for="(v, k) in item.content" :key="k" class="content-item">
                <span class="content-key">{{ k }}:</span>
                <span class="content-value">{{ v }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div v-if="samples.length === 0" class="empty-state">
        <span class="empty-icon">📋</span>
        <p>暂无样品数据</p>
        <button v-if="isLoggedIn && isAdmin" @click="showAddModal = true" class="add-first-btn">
          添加第一个样品
        </button>
      </div>
    </div>

    <!-- 新增/编辑样品弹窗 -->
    <div v-if="showAddModal || showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ showEditModal ? '编辑样品' : '新增样品' }}</h3>
                  <button @click="closeModal" class="close-btn">
          <span class="icon">✕</span>
        </button>
        </div>
        
        <form @submit.prevent="handleSubmit" class="sample-form">
          <div class="form-row">
            <div class="form-group">
              <label>年份 *</label>
              <input v-model="sampleForm.year" type="number" required placeholder="请输入年份" />
            </div>
            <div class="form-group">
              <label>日期 *</label>
              <input v-model="sampleForm.date" type="date" required />
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>样品编号 *</label>
              <input v-model="sampleForm.sample_code" type="text" required placeholder="请输入样品编号" />
            </div>
            <div class="form-group">
              <label>样品名称 *</label>
              <input v-model="sampleForm.sample_name" type="text" required placeholder="请输入样品名称" />
            </div>
          </div>
          
          <div class="form-group">
            <label>含量信息 *</label>
            <div class="content-inputs">
              <div v-for="(content, index) in sampleForm.content" :key="index" class="content-input-row">
                <input 
                  v-model="content.key" 
                  type="text" 
                  placeholder="属性名" 
                  class="content-key-input"
                />
                <input 
                  v-model="content.value" 
                  type="text" 
                  placeholder="属性值" 
                  class="content-value-input"
                />
                <button type="button" @click="removeContent(index)" class="remove-btn">
                  <span class="icon">−</span>
                </button>
              </div>
              <button type="button" @click="addContent" class="add-content-btn">
                <span class="icon">+</span>
                添加含量项
              </button>
            </div>
          </div>
          
          <div class="form-actions">
            <button type="button" @click="closeModal" class="cancel-btn">取消</button>
            <button type="submit" :disabled="loading" class="submit-btn">
              {{ loading ? '保存中...' : (showEditModal ? '更新' : '创建') }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { sampleAPI } from '@/services/api';

export default {
  name: 'SampleList',
  data() {
    return {
      samples: [],
      keyword: '',
      showAddModal: false,
      showEditModal: false,
      loading: false,
      sampleForm: {
        year: new Date().getFullYear(),
        date: new Date().toISOString().split('T')[0],
        sample_code: '',
        sample_name: '',
        content: [{ key: '', value: '' }]
      },
      editingId: null
    };
  },
  computed: {
    isLoggedIn() {
      return !!localStorage.getItem('token');
    },
    isAdmin() {
      return this.currentUser && this.currentUser.role === 'admin';
    },
    currentUser() {
      const userStr = localStorage.getItem('user');
      return userStr ? JSON.parse(userStr) : {};
    },
    isFormValid() {
      return this.sampleForm.year && 
             this.sampleForm.date && 
             this.sampleForm.sample_code && 
             this.sampleForm.sample_name &&
             this.sampleForm.content.some(item => item.key && item.value);
    }
  },
  created() {
    this.fetchSamples();
  },
  methods: {
    async fetchSamples() {
      try {
        const data = await sampleAPI.getSamples(this.keyword);
        this.samples = data.data || [];
      } catch (error) {
        console.error('获取样品列表失败:', error);
      }
    },
    
    editSample(item) {
      this.editingId = item.id;
      this.sampleForm = {
        year: item.year,
        date: item.date,
        sample_code: item.sample_code,
        sample_name: item.sample_name,
        content: Object.entries(item.content).map(([key, value]) => ({ key, value }))
      };
      this.showEditModal = true;
    },
    
    async deleteSample(id) {
      if (!confirm('确定要删除该样品吗？')) return;
      
      try {
        const data = await sampleAPI.deleteSample(id);
        if (data.success) {
          this.fetchSamples();
        } else {
          alert(data.error || '删除失败');
        }
      } catch (error) {
        alert('删除失败');
      }
    },
    
    addContent() {
      this.sampleForm.content.push({ key: '', value: '' });
    },
    
    removeContent(index) {
      if (this.sampleForm.content.length > 1) {
        this.sampleForm.content.splice(index, 1);
      }
    },
    
    async handleSubmit() {
      if (!this.isFormValid) return;
      
      this.loading = true;
      
      try {
        const contentObj = {};
        this.sampleForm.content.forEach(item => {
          if (item.key && item.value) {
            contentObj[item.key] = item.value;
          }
        });
        
        const sampleData = {
          year: parseInt(this.sampleForm.year),
          date: this.sampleForm.date,
          sample_code: this.sampleForm.sample_code,
          sample_name: this.sampleForm.sample_name,
          content: contentObj
        };
        
        let data;
        if (this.showEditModal) {
          data = await sampleAPI.updateSample(this.editingId, sampleData);
        } else {
          data = await sampleAPI.createSample(sampleData);
        }
        
        if (data.success) {
          this.closeModal();
          this.fetchSamples();
        } else {
          alert(data.error || '操作失败');
        }
      } catch (error) {
        alert('操作失败');
      } finally {
        this.loading = false;
      }
    },
    
    closeModal() {
      this.showAddModal = false;
      this.showEditModal = false;
      this.editingId = null;
      this.resetForm();
    },
    
    resetForm() {
      this.sampleForm = {
        year: new Date().getFullYear(),
        date: new Date().toISOString().split('T')[0],
        sample_code: '',
        sample_name: '',
        content: [{ key: '', value: '' }]
      };
    },
    
    goToProfile() {
      this.$router.push('/profile');
    },
    
    formatDate(dateString) {
      if (!dateString) return '';
      
      try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return dateString;
        
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        
        return `${year}年${month}月${day}日`;
      } catch (error) {
        return dateString;
      }
    }
     }
};
</script>

<style scoped>
@import url('//at.alicdn.com/t/c/font_4444444_abcdefg.css');

.sample-list-bg {
  min-height: 100vh;
  background: #f8fafc;
  padding: 0 0 40px 0;
}

.sample-list-header {
  background: #5060ff;
  color: #fff;
  padding: 32px 0 18px 0;
  text-align: center;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  margin-bottom: 18px;
}

.header-top h2 {
  margin: 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.1);
  transition: background 0.3s;
}

.user-info:hover {
  background: rgba(255, 255, 255, 0.2);
}

.user-name {
  font-size: 14px;
  font-weight: 500;
}

.user-info i {
  font-size: 16px;
}

.search-bar {
  margin-top: 18px;
  display: flex;
  justify-content: center;
  gap: 15px;
  flex-wrap: wrap;
  align-items: center;
}

.search-input-group {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e0e7ff;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-bar input {
  padding: 8px 12px;
  border: none;
  font-size: 15px;
  width: 200px;
  outline: none;
  background: transparent;
}

.search-btn {
  padding: 8px 16px;
  border: none;
  background: #5060ff;
  color: #fff;
  font-weight: 600;
  cursor: pointer;
  font-size: 15px;
  transition: background 0.2s;
  border-radius: 0;
}

.search-btn:hover {
  background: #4050e0;
}

.add-btn {
  padding: 8px 16px;
  border-radius: 8px;
  border: none;
  background: #ffb300;
  color: #fff;
  font-weight: 600;
  cursor: pointer;
  font-size: 15px;
  transition: background 0.2s;
  display: flex;
  align-items: center;
  gap: 5px;
}

.add-btn:hover {
  background: #ffa000;
}

.icon {
  font-size: 16px;
  line-height: 1;
}

.sample-cards {
  margin: 24px auto 0 auto;
  max-width: 1200px;
  padding: 0 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.sample-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(80, 112, 255, 0.06);
  padding: 20px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.sample-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(80, 112, 255, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.sample-title h3 {
  margin: 0 0 4px 0;
  font-size: 1.2rem;
  color: #333;
}

.sample-code {
  background: #f0f7ff;
  color: #5060ff;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.edit-btn {
  background: #e3f2fd;
  color: #1976d2;
}

.edit-btn:hover {
  background: #bbdefb;
}

.delete-btn {
  background: #ffebee;
  color: #d32f2f;
}

.delete-btn:hover {
  background: #ffcdd2;
}

.card-content {
  color: #666;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.label {
  font-weight: 500;
  color: #333;
}

.value {
  color: #666;
}

.content-details {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.content-items {
  margin-top: 8px;
}

.content-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-size: 0.9rem;
}

.content-key {
  font-weight: 500;
  color: #333;
}

.content-value {
  color: #666;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
  display: block;
}

.empty-state p {
  margin: 0 0 20px 0;
  font-size: 1.1rem;
}

.add-first-btn {
  background: #5060ff;
  color: #fff;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  transition: background 0.2s;
}

.add-first-btn:hover {
  background: #4050e0;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: #fff;
  border-radius: 16px;
  padding: 30px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.modal-header h3 {
  margin: 0;
  font-size: 1.3rem;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  color: #999;
  cursor: pointer;
}

.sample-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #333;
}

.form-group input {
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 1rem;
  outline: none;
  transition: border-color 0.2s;
}

.form-group input:focus {
  border-color: #5060ff;
}

.content-inputs {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.content-input-row {
  display: flex;
  gap: 8px;
  align-items: center;
}

.content-key-input,
.content-value-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 0.9rem;
}

.remove-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  background: #ffebee;
  color: #d32f2f;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-content-btn {
  background: #e8f5e8;
  color: #2e7d32;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  gap: 5px;
  align-self: flex-start;
}

.form-actions {
  display: flex;
  gap: 16px;
  margin-top: 20px;
}

.cancel-btn,
.submit-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f0f0f0;
  color: #666;
}

.cancel-btn:hover {
  background: #e0e0e0;
}

.submit-btn {
  background: #5060ff;
  color: #fff;
}

.submit-btn:hover:not(:disabled) {
  background: #4050e0;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .sample-cards {
    grid-template-columns: 1fr;
    padding: 0 16px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .search-bar {
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
  
  .search-input-group {
    width: 100%;
    max-width: 300px;
  }
  
  .search-bar input {
    width: 100%;
    flex: 1;
  }
}
</style> 